package edu.hunau.demo;

import edu.hunau.aop.handler.MyHandler;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.lang.reflect.Proxy;

/**
 * @author hb
 * @date 2022-11-29 11:37:25
 */
public class MyProxyFactory {

    public static Object getProxy(Object target) throws Exception {
        MyHandler myHandler = new MyHandler();
        myHandler.setTarget(target);
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), myHandler);
    }
    //追加xml配置文件时修改
    private static MyHandler myHandler;
    public static Object getBean(String targetName) throws Exception {
        Object target = createObject(targetName);
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), myHandler);
    }

    public static Object createObject(String name) throws Exception {
        Object obj = null;
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File("./src/main/resources/beans.xml"));
        Element root = doc.getRootElement();
        Element child = (Element)root.selectNodes("bean[@id='"+name+"']").get(0);
        String proxyClass=child.attributeValue("class");
        Element ch = (Element) child.selectNodes("property").get(0);
        String proName = ch.attributeValue("name");
        String loc = ch.attributeValue("loc");
        Element tagetE = (Element) root.selectNodes("bean[@id='" + loc + "']").get(0);
        String tagetClass = tagetE.attributeValue("class");
        obj = Class.forName(tagetClass).newInstance();
        myHandler=(MyHandler)Class.forName(proxyClass).newInstance();
        myHandler.setTarget(obj);
        System.out.println(proxyClass);
        return obj;
    }

}
